package com.cts.learninglibrary.config.shiro;

import com.cts.learninglibrary.exception.LoginErrorException;
import com.cts.learninglibrary.pojo.User;
import com.cts.learninglibrary.service.UserService;
import com.cts.learninglibrary.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

/**
 * @author arctique
 * @date 2020/8/24 9:39
 */
@Slf4j
public class UserRealm extends AuthorizingRealm {

    private final char STATUS_STOP = '1';

    @Autowired
    private UserService userService;


    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("[授权开始...]");

        // 创建授权对象
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 获取当前用户信息
//        log.info("[授权] : {}", JsonUtil.objToString(principalCollection.getPrimaryPrincipal()));
//        User user = null;
//        Object o = principalCollection.getPrimaryPrincipal();
//
//        log.info("[授权user] : {}", JsonUtil.objToString(o));
//        user = CommonConverterUtil.convert(o, User.class);
//
//        // 获取角色信息
//        Role role = roleService.findById(user.getRoleId());
//
//        if (role == null) {
//            throw new AuthException(-1, "角色为空");
//        }
//        simpleAuthorizationInfo.addRole(role.getName());
//        // 获取权限信息
//        List<RolePermission> rolePermissionList = rolePermissionService.findByRoleId(role.getId());
//        if (CollectionUtils.isEmpty(rolePermissionList)) {
//            throw new AuthException(-1, "此角色没有对应的访问权限");
//        }
//
//        List<Integer> powerIds = new ArrayList<>();
//        if (!CollectionUtils.isEmpty(rolePermissionList)) {
//            for (RolePermission rolePermission : rolePermissionList) {
//                powerIds.add(rolePermission.getPermissionId());
//            }
//        }
//        List<Permission> permissionList = permissionService.findByPowerIds(powerIds);
//        if (!CollectionUtils.isEmpty(permissionList)) {
//            simpleAuthorizationInfo.addRole(role.getName());
//            for (Permission permission : permissionList) {
//                if (permission.getParentId() != 0) {
//                    simpleAuthorizationInfo.addStringPermission(permission.getCode());
//                }
//            }
//        }
        return simpleAuthorizationInfo;
    }

    /**
     * 认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("[认证开始...]");

        // 获取登录用户信息
        String username = authenticationToken.getPrincipal().toString();

        log.info("[username] : {}", username);
        if (StringUtils.isEmpty(username)) {
            throw new LoginErrorException(-1, "用户名为空");
        }

        User user = null;
        try {
            user = userService.findByUsername(username);
            log.info("[user] : {}", JsonUtil.objToString(user));
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        if (user == null) {
            // 用户不存在
            throw new LoginErrorException(-1, "不存在此帐号");
        } else if (user.getStatus() == STATUS_STOP) {
            // 用户账号停用
            throw new LoginErrorException("用户【" + user.getUsername() + "】已经停用");
        }

        SimpleAuthenticationInfo simpleAuthenticationInfo =
                new SimpleAuthenticationInfo(user, user.getPassword(), this.getName());
        simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(user.getSalt()));
        return simpleAuthenticationInfo;
    }
}
